﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using Soufun.DAL;
using Soufun.Model;
using System.Threading;

namespace Soufun
{
    public partial class ProjectHouseTpyeStatisticsForm : DevExpress.XtraEditors.XtraForm
    {
        public ProjectHouseTpyeStatisticsForm()
        {
            InitializeComponent();
        }

        private void ProjectHouseTpyeStatisticsForm_Load(object sender, EventArgs e)
        {
            Thread t = new Thread(LoadProjectUrlList) 
            { IsBackground = true };
            t.Start();
        }
        private DProjectUrl _dProjectUrl = new DProjectUrl();
        private DProjectDetail _dProjectDetail = new DProjectDetail();
        private DProjectArea _dProjectArea = new DProjectArea();
        private DHouseType _dHouseType = new DHouseType();
        readonly Hashtable _htResultList = Hashtable.Synchronized(new Hashtable());

        private void LoadProjectUrlList()
        {
            BeginInvoke(new MethodInvoker(() =>
            {
                comboBox_projectList.Properties.Items.Clear();
            }));
            ImageComboBoxItem item = new ImageComboBoxItem();
            item.Description = "所有项目";
            item.Value = "所有项目";
            item.ImageIndex = 0;
            BeginInvoke(new MethodInvoker(() =>
            {
                comboBox_projectList.Properties.Items.Add(item);
            }));

            DataSet ds = _dProjectUrl.GetList("");
            if (ds == null || ds.Tables.Count == 0)
            {
                XtraMessageBox.Show("未能加载项目web列表，请检查数据库连接是否正常！");
                return;
            }             
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                string projectName = row["ProjectName"].ToString();
                string projecturl = row["ProjectUrl"].ToString();
                ImageComboBoxItem item2 = new ImageComboBoxItem();
                item2.Description = projectName;
                item2.Value = projecturl;
                item2.ImageIndex = int.Parse(row["Id"].ToString());
                BeginInvoke(new MethodInvoker(() =>
                {
                    comboBox_projectList.Properties.Items.Add(item2);
                }));
            }
            BeginInvoke(new MethodInvoker(() =>
                {
                    comboBox_projectList.SelectedIndex = 0;
                }));

        }
        private bool _isAll;

        private void btn_select_Click(object sender, EventArgs e)
        {
            if (!CheckControl())
            {
                return;
            }
            _htResultList.Clear();
            gridControl1.DataSource = null;
            btn_select.Enabled = false;
            comboBox_projectList.Enabled = false; 
            comboBox_insertTimeList.Enabled = false;
            progressBar1.Visible = true;
            progressBar1.Position = 0;

            if (comboBox_projectList.SelectedIndex == 0)
            {
                _isAll = true;
                Thread tAll = new Thread(GetResultOfAllProject)
                    {IsBackground = true};
                tAll.Start();
            }
            else
            {
                _isAll = false;
                ProjectNameIdInfo info = new ProjectNameIdInfo();
                info.Name = comboBox_projectList.Properties.Items[
                    comboBox_projectList.SelectedIndex].Description;
                info.Id = comboBox_projectList.Properties.Items[
                comboBox_projectList.SelectedIndex].ImageIndex;
                Thread t = new Thread(GetResult) { IsBackground = true };
                t.Start(info);  
            }
           
        }

        private void GetResultOfAllProject()
        {
            BeginInvoke(new MethodInvoker(() =>
            {
                progressBar1.Position = 0;
                progressBar1.Properties.Minimum = 0;
                progressBar1.Properties.Maximum =
                comboBox_projectList.Properties.Items.Count-1;

            }));   
            for (int i = 1; i <comboBox_projectList.Properties.Items.Count; i++)
            {                
                ProjectNameIdInfo info = new ProjectNameIdInfo();
                info.Id = comboBox_projectList.Properties.Items[
                    i].ImageIndex;
                info.Name = comboBox_projectList.Properties.Items[
                    i].Description;
                GetResult(info);
                BeginInvoke(new MethodInvoker(() =>
                    {
                        progressBar1.Position = i;
                       lb_notice.Text = "完成进度：" + i + "/" 
                        + (comboBox_projectList.Properties.Items.Count);
                }));
            }
            BindResult();
        }

        private void GetResult(object objNameId)
        {            
            try
            {
                ProjectNameIdInfo info = (ProjectNameIdInfo) objNameId;
                int projectId = (int) info.Id;
                DateTime insertTime = DateTime.Parse(
                   comboBox_insertTimeList.SelectedItem.ToString());
                StringBuilder strWhere = new StringBuilder();
                strWhere.Append("ProjectId=");
                strWhere.Append(projectId);               
                DataSet dsArea = _dProjectArea.GetList(strWhere.ToString());
                strWhere.Append(" and InsertTime ='");
                strWhere.Append(insertTime);
                strWhere.Append("'");
                DataSet ds = _dProjectDetail.GetList(strWhere.ToString());
                DataSet dsHouseType = _dHouseType.GetProjectHouseTypeList(projectId);
                if (ds == null || ds.Tables.Count == 0 ||
                    dsArea == null || dsArea.Tables.Count == 0||
                    dsHouseType==null||dsHouseType.Tables.Count==0)
                {
                    //XtraMessageBox.Show("查询数据库时发生异常，请检查数据库连接是否正常！");
                    return;
                } 
                DataTable dtHouseType = dsHouseType.Tables[0];
                DataTable dtData = ds.Tables[0];
                DataTable dtArea = dsArea.Tables[0];
                if (!_isAll)
                {
                    BeginInvoke(new MethodInvoker(() =>
                    {
                        progressBar1.Position = 0;
                        progressBar1.Properties.Minimum = 0;
                        progressBar1.Properties.Maximum = dtData.Rows.Count;
                    }));    
                }                
                for (int i = 0; i < dtData.Rows.Count; i++)
                {
                    if (!_isAll)
                    {
                        BeginInvoke(new MethodInvoker(() =>
                        {
                            progressBar1.Position = i + 1;
                      
                                lb_notice.Text = "完成进度：" + i
                                + "/" + (dtData.Rows.Count - 1);
                                                   
                        }));
                    }                
                    DataRow drData = dtData.Rows[i];
                    DataRow drArea = dtArea.Rows[i];
                    
                    string strHouseAttribute = drData["HouseAttribute"].ToString();
                    strHouseAttribute = strHouseAttribute.Remove(strHouseAttribute.Length - 1, 1);
                    string strArea = drArea["ProjectAreaString"].ToString();
                    string[] houseArray = strHouseAttribute.Split(',');
                    string[] areaArray = strArea.Split(',');
                    if (houseArray.Length != areaArray.Length)
                    {
                        Console.WriteLine("项目面积表中的数据长度不匹配！");
                    }

                    for (int j = 0; j < houseArray.Length; j++)
                    {
                        string state = houseArray[j];
                        if (state == "-1")
                        {
                            continue;
                        }
                        double area = double.Parse(areaArray[j]);
                        if (area==0)
                        {
                            Console.WriteLine("查询到面积为0，过滤...");
                            continue;
                        }
                        DataRow[] typeRow = dtHouseType.Select(
                            "HouseArea=" + area);                        
                        string houseType = "";
                        if (typeRow.Length>0)
                        {
                            houseType = typeRow[0]["HouseType"].ToString();
                        }
                        string key =info.Name+"|"+ houseType;
                        key += "|" + area;
                        CountInfo countInfo = _htResultList[key] as CountInfo;
                        if (countInfo == null)
                        {
                            countInfo = new CountInfo();
                            countInfo.Amount = 1;
                            if (state == "0")
                            {
                                countInfo.OnSaleCount = 1;
                            }
                            _htResultList[key] = countInfo;
                        }
                        else
                        {
                            countInfo.Amount++;
                            if (state == "0")
                            {
                                countInfo.OnSaleCount++;
                            }
                        }
                    }
                }
                if (!_isAll)
                {
                    BindResult();
                }
              
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("发生异常：" + ex.Message);
                BeginInvoke(new MethodInvoker(() =>
                {                    
                    btn_select.Enabled = true;
                    comboBox_projectList.Enabled = true; 
                    comboBox_insertTimeList.Enabled = true;
                }));
            }
           
        }

        private void BindResult()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("项目名称");
            dt.Columns.Add("户型");
            dt.Columns.Add("户型面积");
            dt.Columns.Add("总套数");
            dt.Columns.Add("已售套数");
            dt.Columns.Add("可售套数");
            dt.Columns.Add("可售面积");

            foreach (DictionaryEntry dictionaryEntry in _htResultList)
            {
                string key = dictionaryEntry.Key.ToString();
                string[] keyArray = key.Split('|');
                DataRow row = dt.NewRow();
                row["项目名称"] = keyArray[0];
                row["户型"] = keyArray[1];
                row["户型面积"] = keyArray[2];
                CountInfo countInfo = dictionaryEntry.Value as CountInfo;
                row["总套数"] = countInfo.Amount;
                row["可售套数"] = countInfo.OnSaleCount;
                int saledCount = countInfo.Amount - countInfo.OnSaleCount;
                row["已售套数"] = saledCount;
                float onSaleArea = countInfo.OnSaleCount
                    * float.Parse(keyArray[2]);
                row["可售面积"] = onSaleArea.ToString("f2");
                dt.Rows.Add(row);
            }
            BeginInvoke(new MethodInvoker(() =>
            {
                gridControl1.DataSource = dt;
                btn_select.Enabled = true;
                comboBox_projectList.Enabled = true;
                comboBox_insertTimeList.Enabled = true;
                XtraMessageBox.Show("统计完成");
                progressBar1.Visible = false;
            }));
        }
   

        private void comboBox_projectList_SelectedIndexChanged(object sender, EventArgs e)
        {
            
            comboBox_insertTimeList.Properties.Items.Clear(); 
            gridControl1.DataSource = null;           
            if (comboBox_projectList.SelectedIndex == -1)
            {
                return;
            }             
            comboBox_projectList.Enabled = false; 
            comboBox_insertTimeList.Enabled = false;

            Thread t = new Thread(BindInsertTimeList) { IsBackground = true };
            t.Start();
        }

        private void BindInsertTimeList()
        {
            DataSet ds;
            if (comboBox_projectList.SelectedIndex==0)
            {
                ds = _dProjectDetail.GetAllInsetTimeList();
            }
            else
            {
                int projectId = comboBox_projectList.Properties.Items[
                    comboBox_projectList.SelectedIndex].ImageIndex;
                ds = _dProjectDetail.GetInsetTimeList(projectId);    
            }            
            if (ds == null || ds.Tables.Count == 0)
            {
                XtraMessageBox.Show("加载抓取数据时间列表异常，请检查数据库连接是否正常！");
                return;
            }
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                string insertTime = row["InsertTime"].ToString();
                BeginInvoke(new MethodInvoker(() =>
                {
                    ImageComboBoxItem item = new ImageComboBoxItem();
                    item.Description = insertTime;
                    item.Value = insertTime;
                    comboBox_insertTimeList.Properties.Items.Add(item);                    
                }));
            }
           
            BeginInvoke(new MethodInvoker(() =>
            {
                comboBox_projectList.Enabled = true;
                comboBox_insertTimeList.Enabled = true;
               
            }));
        }

        private class CountInfo
        {
            public int Amount { get; set; }
            public int OnSaleCount { get; set; }
        }

        private class ProjectNameIdInfo
        {
            public int Id { get; set; }
            public string Name { get; set; }             
        }

        private bool CheckControl()
        {
            if (comboBox_projectList.SelectedIndex<0)
            {
                XtraMessageBox.Show("请选择想要查询的项目！");
                comboBox_projectList.Focus();
                return false;
            }
          
            if (comboBox_insertTimeList.SelectedIndex<0)
            {
                XtraMessageBox.Show("请选择统计的截止日期！");
                comboBox_insertTimeList.Focus();
                return false;
            }
            return true;
        }

        #region 导出Excel

        private void btn_toExcel1_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                return;
            }
            string fileName = comboBox_projectList.SelectedItem.ToString()
             + DateTime.Parse(comboBox_insertTimeList.SelectedItem.ToString())
             .ToString("MM月dd号HH点mm分")+"住房户型面积销售统计";
            saveFileDialog1.FileName = fileName;
            saveFileDialog1.Filter = "Excel文件(*.xls)|*.xls";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                gridView1.ExportToXls(saveFileDialog1.FileName);
                XtraMessageBox.Show("Excel导出完成！");
            }
        }         
        #endregion

        #region 窗体效果
        //private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        //{
        //    pictureBox1.Image = Properties.Resources.btn_exit;
        //    Cursor = Cursors.Hand;
        //}

        //private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        //{
        //    pictureBox1.Image = Properties.Resources.btn_exitPressDown;
        //    Cursor = Cursors.Arrow;
        //}

        private void pictureEdit_exit_Click(object sender, EventArgs e)
        {
            Close();
        }

        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }

        private void btn_MouseHover(object sender, EventArgs e)
        {
            Cursor = Cursors.Hand;
        }

        private void btn_MouseLeave(object sender, EventArgs e)
        {
            Cursor = Cursors.Arrow;
        }

        private void Form_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                this.Close();
            }
        }

        #endregion
    }
}